package com.pet.controller.webUser;

import com.pet.constant.JwtClaimsConstant;
import com.pet.dto.web.UserInformationDTO;
import com.pet.dto.web.UserLoginDTO;
import com.pet.entity.Employee;
import com.pet.properties.JwtProperties;
import com.pet.result.Result;
import com.pet.service.UserInformationService;
import com.pet.utils.JwtUtil;
import com.pet.vo.web.EmployeeLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserInformationController {

    @Autowired
    private UserInformationService userInformationService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);

        Employee employee = userInformationService.login(userLoginDTO);//进行登录判定

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();//这个HashMap的键（key）是String类型，值（value）是Object类型。
        claims.put(JwtClaimsConstant.USER_ID, employee.getId());
        String token = JwtUtil.createJWT(//生成jwt令牌的操作类
                jwtProperties.getAdminSecretKey(),//生成相关变量属性
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();
        //返回登录信息包含成功后的token
        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }


    /**
     * 修改用户信息
     */
    @PutMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody UserInformationDTO userInformationDTO){
        log.info("修改用户信息");
        userInformationService.updateUserInfo(userInformationDTO);
        return Result.success();
    }

    /**
     * 注册用户
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserLoginDTO userLoginDTO){
        log.info("注册用户:{}",userLoginDTO);
        userInformationService.insertUserInformation(userLoginDTO);
        return Result.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody UserLoginDTO userLoginDTO){
        log.info("修改密码:{}",userLoginDTO);
        userInformationService.updatePassword(userLoginDTO);
        return Result.success();
    }


}
